#!/bin/bash

source ./color.sh

# 检测/生成公钥
if [ ! -f ~/.ssh/id_rsa.pub ]; then
    ssh-keygen -f ~/.ssh/id_rsa -t rsa -N ''
fi

# 打印主机列表
msg green "======================================================================="
msg green "hosts: "
msg green "$(for host in $(awk '{print $1}' passwd.txt); do echo -e "\t$host"; done)"
msg green "======================================================================="

# 等待5秒
for((i=5; i>0; i--)); do
    echo -en "${CGREEN} Wait $i ... ${CEND}\r"
    sleep 1;
done

# 发送公钥到远程主机
i=1
len=$(awk '{print $1}' passwd.txt | wc -l)
for host in $(awk '{print $1}' passwd.txt); do
    user=$(awk -v I="$host" '{if(I==$1)print $2}' passwd.txt)
    pass=$(awk -v I="$host" '{if(I==$1)print $3}' passwd.txt)
    port=$(awk -v I="$host" '{if(I==$1)print $4}' passwd.txt)
    port=${port:-22}

    # ping 检测
    msg green "======================================================================="
    ping -i 0.2 -c 3 -W 1 $host >& /dev/null
    if test $? -ne 0; then
        msg red "---> $host [$i/$len] ping no"
        exit 1
    else
        msg green "---> $host [$i/$len] ping ok"
    fi

    # 删除重复的公钥
    check_key=$(cat ~/.ssh/known_hosts | grep "$host")
    [ -z "$check_key" ] && sed -i "/$host/d" ~/.ssh/known_hosts

    # 秘钥登录
    cat /etc/hosts | grep -v '^#' | grep $host >& /dev/null
    if test $? -eq 0; then
        hostaddr=$(cat /etc/hosts | grep -v '^#' | grep $host | awk '{print $1}')
        hostname=$(cat /etc/hosts | grep -v '^#' | grep $host | awk '{print $2}')
        
        expect login.exp $hostaddr $user $pass $port $(eval echo ~$user)
        expect login.exp $hostname $user $pass $port $(eval echo ~$user)
    else
        expect login.exp $host $user $pass $port $(eval echo ~$user)
    fi
    let i++
done
